# Bot for "combine the names of everyone else online into one big name" thread
# by Cee Pee

import random
import re
import forumapi
from deps.PageRequest import PageRequest

def settings(settings):
	methods = ["chars", "byspace", "magic", "anagram"]
	method = "chars"
	
	settings.add_option("--method", type="choice", choices=methods, default=method, help="scrambling method")
	settings.add_arg("thread", type="int", help="thread ID to post in")

def main(me, options, args):
	page = me.get_page("index.php")
	soup = me.soup(page)
	
	table = soup.find(id="collapseobj_forumhome_activeusers")
	line = table.find("div", "smallfont").findAll("div")[1]
	links = line.findAll("a")
	
	data = []
	for link in links:
		if link.string is None:
			# Powers
			link = link.find("span")
			if link.string is None:
				continue
		
		#print(link.string)
		linktext = forumapi.convert_entities(link.string)
		if options.method == "chars":
			# This results in a lot of empty entries but that doesn't matter.
			stuff = re.split("(.)", linktext)
		elif options.method == "byspace":
			stuff = linktext.split(" ")
		elif options.method in ("magic", "anagram"):
			stuff = re.split('([A-Z]?[^A-Z\s_]+)[\s_]*(?=[A-Z]?)', linktext)
		
		data.extend([item for item in stuff if item])
	
	random.shuffle(data)
	if options.method == "chars":
		text = "".join(data)
	elif options.method in ("byspace", "magic"):
		text = " ".join(data)
	elif options.method == "anagram":
		headers = {
			"User-Agent": "Mozilla/4.2",
			"Referer": "http://www.arrak.fi/en/ag",
			"Accept": "text/html,*/*;q=0.9",
			"Accept-Language": "en-US,en",
		}
		
		sample = "".join(random.sample(data, min(len(data), 10)))
		print(sample)
		
		response = PageRequest("http://www.arrak.fi/cgi-bin/inline_ag.pl?sourcetext={0}&lang=English&lines=1&maxword=5&sort=4".format(sample), encoding=site.encoding, headers=headers)
		
		anagram_soup = me.soup(response)
		text = anagram_soup.find("pre").string
	
	# TODO: Test for encoding errors
	print(text)
	
	post = me.prepare_post(t=args.thread)
	post.message = text
	result = post.post()
	print(repr(result))

if __name__ == "__main__":
	forumapi.run(main, options=settings, supported_types=["vbulletin"])
